/**
 * 解析任意颜色字符串为 { r, g, b, a }
 * 支持 #RGB, #RGBA, #RRGGBB, #RRGGBBAA, rgb(), rgba()
 */
export function parseColor(color: string): { r: number, g: number, b: number, a: number } {
  const clean = color.replace(/\s/g, '')
  if (clean.startsWith('#')) {
    let hex = clean.slice(1)
    if (hex.length === 3)
      hex = `${hex.split('').map(c => c + c).join('')}ff`
    else if (hex.length === 4)
      hex = hex.split('').map(c => c + c).join('')
    else if (hex.length === 6)
      hex += 'ff'
    if (hex.length !== 8)
      throw new Error(`Invalid hex color: ${color}`)
    const r = Number.parseInt(hex.slice(0, 2), 16)
    const g = Number.parseInt(hex.slice(2, 4), 16)
    const b = Number.parseInt(hex.slice(4, 6), 16)
    const a = Number.parseInt(hex.slice(6, 8), 16) / 255
    return { r, g, b, a }
  }
  if (clean.startsWith('rgb')) {
    const match = clean.match(/rgba?\(([^)]+)\)/)
    if (!match)
      throw new Error(`Invalid RGB color format: ${color}`)
    const values = match[1].split(',').map(v => Number.parseFloat(v.trim()))
    if (values.length < 3)
      throw new Error(`Invalid RGB color format: ${color}`)
    const [r, g, b, a = 1] = values
    return { r, g, b, a }
  }

  throw new Error(`Unsupported color format: ${color}`)
}

/**
 * 将颜色转换为十六进制格式（带透明度）
 * @param color 任意颜色字符串
 * @param alpha 可选，覆盖透明度
 */
export function toHexColor(color: string, alpha?: number): string {
  const { r, g, b, a } = parseColor(color)
  const useAlpha = alpha !== undefined ? alpha : a
  return (
    `#${
      [r, g, b].map(x => Math.round(x).toString(16).padStart(2, '0')).join('')
    }${Math.round(useAlpha * 255).toString(16).padStart(2, '0')}`
  )
}

/**
 * 在两个颜色之间插值，支持透明度
 * @param fromColor 起始色
 * @param toColor 目标色
 * @param t 0~1
 * @returns 过渡色的rgba字符串
 */
export function mixColor(fromColor: string, toColor: string, t: number): string {
  const from = parseColor(fromColor)
  const to = parseColor(toColor)
  const r = Math.round(from.r + (to.r - from.r) * t)
  const g = Math.round(from.g + (to.g - from.g) * t)
  const b = Math.round(from.b + (to.b - from.b) * t)
  const a = from.a + (to.a - from.a) * t
  return `rgba(${r},${g},${b},${a.toFixed(3)})`
}

/**
 * 根据背景色自动选择黑色或白色文本色
 * @param backgroundColor 背景色（支持任意格式）
 * @param threshold 亮度阈值，默认186
 * @returns '#000' 或 '#fff'
 */
export function getContrastColor(backgroundColor: string, threshold = 186): string {
  const { r, g, b } = parseColor(backgroundColor)
  const brightness = (r * 299 + g * 587 + b * 114) / 1000
  return brightness > threshold ? '#000' : '#fff'
}
